'use strict';

/**
 * Recommendation.js controller
 *
 * @description: A set of functions called "actions" for managing `Recommendation`.
 */

module.exports = {

  /**
   * Retrieve recommendation records.
   *
   * @return {Object|Array}
   */

  find: async (ctx, next, { populate } = {}) => {
    if (ctx.query._q) {
      return strapi.services.recommendation.search(ctx.query);
    } else {
      return strapi.services.recommendation.fetchAll(ctx.query, populate);
    }
  },

  /**
   * Retrieve a recommendation record.
   *
   * @return {Object}
   */

  findOne: async (ctx) => {
    const result = await strapi.services.recommendation.fetch(ctx.params);
    if (!result) {
      return
    }
    const data = result.toJSON()
    const carFilters = {};
    if (data.minPrice) {
      carFilters.price_gte = data.minPrice;
    }
    if (data.maxPrice) {
      carFilters.price_lte = data.minPrice;
    }
    if (data.beginYear) {
      carFilters.year_gte = data.beginYear;
    }
    if (data.endYear) {
      carFilters.year_lte = data.endYear;
    }
    if (data.makes) {
      carFilters.make_in = data.makes.split(',');
    }
    const cars = await strapi.services.car.fetchAll(carFilters);
    data.cars = cars.toJSON()
    return data;
  },

  /**
   * Count recommendation records.
   *
   * @return {Number}
   */

  count: async (ctx, next, { populate } = {}) => {
    return strapi.services.recommendation.count(ctx.query, populate);
  },

  /**
   * Create a/an recommendation record.
   *
   * @return {Object}
   */

  create: async (ctx) => {
    return strapi.services.recommendation.add(ctx.request.body);
  },

  /**
   * Update a/an recommendation record.
   *
   * @return {Object}
   */

  update: async (ctx, next) => {
    return strapi.services.recommendation.edit(ctx.params, ctx.request.body) ;
  },

  /**
   * Destroy a/an recommendation record.
   *
   * @return {Object}
   */

  destroy: async (ctx, next) => {
    return strapi.services.recommendation.remove(ctx.params);
  }
};
